import { validaPhone } from '../../../utils/util'
import { API_CONFIG } from '../../../config'
const MAX_IMG_NUM = 5;
const addTextCreate = 'addTextCreate'
const updateTextCreate = 'updateTextCreate'

let interfaceText = addTextCreate
let timer = null

Page({
  /**
   * 页面的初始数据
   */
  data: {
    textUrl: 'https://xwx.gzzmedu.com:6899/pic/wx-x-mai/textCreate/wenzi.png',
    defaultImgUrl: 'https://xwx.gzzmedu.com:6899/pic/wx-x-mai/textCreate/jia.png',
    workDesc: '',
    images: [], // 图片数组
    selectPhotoNum: MAX_IMG_NUM, // 默认显示加号数量
    userName: '', // 用户名
    phone: '', // 电话号码
    localImages: [], // 选择的图片数组,而不是默认获取的图片数组
    interfaceText: '提交'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    interfaceText = addTextCreate
    this.setData({
      interfaceText: '提交'
    })
    this.getTextCreate()
    // wx.showShareMenu({
    //   withShareTicket: true,
    //   menus: ['shareAppMessage', 'shareTimeline']
    // })
  },

  /**
   * @see 获取文创信息
   */
  getTextCreate () {
    wx.showLoading({
      title: '正在初始化信息...'
    })
    const request = {
    }
    wx.$API['workService/getTextCreate'](request).then(res => {
      const { data } = res
      if (data.length > 0) {
        const { content, imageArr, phone, standbyName } = data[0];
        this.setData({
          phone,
          workDesc: content,
          userName: standbyName,
          selectPhotoNum: MAX_IMG_NUM - imageArr.length,
          images: imageArr,
          interfaceText: '修改'
        })
        interfaceText = updateTextCreate
      }
      wx.hideLoading()
    }).catch(error => {
      wx.hideLoading()
      wx.showToast({
        title: error,
        icon: 'none'
      })
      console.log('获取文创信息失败', error);
    })
  },

  /**
   * @see 提交事件
   */
  submit () {
    const { images, phone, userName, workDesc, localImages } = this.data
    if (!userName.trim() || !workDesc.trim()) {
      wx.showToast({
        title: '请填全信息',
        icon: 'none'
      })
      return
    }
    if (!validaPhone.test(phone.trim())) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      })
      return
    }
    wx.showLoading({
      title: '正在提交...'
    })
    const userInfo = wx.getStorageSync('userInfo')
    const schoolConfig = wx.getStorageSync('schoolConfig')
    // 要上传的图片数组
    let uploadImages = images.filter(v => v.chooseImage)
    let oldImages = images.filter(v => !v.chooseImage)
    let newImages = []
    // 上传图片的多个异步任务
    let promiseArr = []
    uploadImages.forEach(path => {
      let pro = new Promise((resolve, reject) => {
        wx.uploadFile({
          url: (API_CONFIG.isDev ? API_CONFIG.devUrl : API_CONFIG.productionUrl) + 'api/school-service-ms/Cci/upload',
          filePath: path.imageUrl,
          name: 'file',
          header: {
            'X-Authorization': wx.getStorageSync('token'),
            'Content-Type': 'multipart/form-data'
          },
          formData: {
            'userId': userInfo.userId,
            schoolCode: schoolConfig.schoolCode
          },
          success (res) {
            const data = JSON.parse(res.data);
            const { result } = data
            if (result) {
              delete result.imageUrl
            }
            newImages.push(result)
            resolve(result)
          },
          fail: err => {
            wx.showToast({
              title: err,
              icon: 'none'
            })
            console.log('图片上传失败', err);
          }
        })
      })
      promiseArr.push(pro)
    })
    Promise.all(promiseArr).then(() => {
      return new Promise((resolve, reject) => {
        const request = {
          "content": workDesc,
          "phone": phone,
          "standbyName": userName,
          "imageArr": oldImages.concat(newImages)
        }
        wx.$API[`workService/${interfaceText}`](request).then(res => {
          wx.hideLoading()
          wx.showToast({
            title: '操作成功',
            icon: 'success'
          })
          this.setData({
            interfaceText: '修改'
          })
          interfaceText = updateTextCreate
        }).catch(error => { reject(error) })
      })
    }).catch(error => {
      wx.hideLoading()
      wx.showToast({
        title: error,
        icon: 'none'
      })
      console.log('文创上传失败', error)
    })
  },

  /**
   * @see 输入框双向绑定
   */
  inputEvent (e) {
    const { name } = e.currentTarget.dataset
    const { value } = e.detail
    clearTimeout(timer)
    timer = setTimeout(() => {
      this.setData({
        [name]: value
      })
    }, 300)
  },

  /**
   * @see 预览图片
   */
  prevImage (e) {
    const { url } = e.currentTarget.dataset
    let arr = this.data.images.map(v => v.imageUrl)
    wx.previewImage({
      current: url,
      urls: arr
    })
  },

  /**
   * @see 删除图片
   */
  clearImg (e) {
    const { index } = e.currentTarget.dataset
    this.data.images.splice(index, 1)
    this.setData({
      images: this.data.images
    })
    const count = MAX_IMG_NUM - this.data.images.length
    this.setData({
      selectPhotoNum: count
    })
  },

  /**
   * @see 选择图片
   */
  chooseImage () {
    let count = MAX_IMG_NUM - this.data.images.length
    wx.chooseImage({
      count,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        // tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFilePaths
        let arr = this.data.images.concat(tempFilePaths)
        let images = arr.map(v => {
          if (typeof v !== 'object') {
            return { imageUrl: v, chooseImage: true }
          } else {
            return v
          }
        })
        this.setData({
          images,
          localImages: this.data.localImages.concat(tempFilePaths)
        })
        count = MAX_IMG_NUM - this.data.images.length
        this.setData({
          selectPhotoNum: count
        })
      }
    })
  },

})